package com.jumi.microservice.controller.api;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.exception.BaseException;
import com.jm.member.common.core.utils.LocalDateTimeUtil;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.core.web.page.TableDataInfo;
import com.jm.member.common.jwt.annon.IgnoreUrlsAnnon;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jm.member.common.redis.service.RedisService;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.config.LocalDateTimeConfig;
import com.jumi.microservice.domain.GoodsSpuDTO;
import com.jumi.microservice.dto.reponse.api.*;
import com.jumi.microservice.dto.request.JmFlowUpdateRequest;
import com.jumi.microservice.dto.request.api.MyTeamQueryRequest;
import com.jumi.microservice.entity.*;
import com.jumi.microservice.enums.*;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.WrapperUtil;
import io.jsonwebtoken.Jwt;
import io.swagger.annotations.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/team")
@Api(tags = "C-团队")
public class TeamController {

    @Resource
    RedisService redisService;

    @Resource
    IJmUserFenxiaoService fenxiaoService;

    @Resource
    IJmUserSalesService salesService;

    @Resource
    IJmUserService userService;

    @Resource
    IJmUserTeamService teamService;

    @Resource
    IJmUserInviteService inviteService;

    @Resource
    IJmUserStatisticsTeamService statisticsTeamService;

    @Resource
    IJmUserStatisticsSalesService statisticsSalesService;

    @Resource
    IJmUserStatisticsFenxiaoService statisticsFenxiaoService;

    @Resource
    IJmUserLevelConfigService levelConfigService;

    @GetMapping("/teamSalesIndex")
    @ApiOperation(value = "店铺业绩首页", response = TeamSalesAggregate.class)
    public ResponseResult teamSalesIndex() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
//        Integer memberId = 17;
        TeamSalesAggregate teamSalesAggregate = new TeamSalesAggregate(getAggregate(memberId));
        LocalDateTime todayMaxTime = LocalDateTimeUtil.getNBeforeMaxTime(0);//今天的最大时间
        LocalDateTime todayMinTime = LocalDateTimeUtil.getNBeforeMinTime(0);//今天的最小事件

        //累计总业绩
        TeamSalesItem salesItem = packTeamSales(null, null, memberId);

        //今天业绩
        TeamSalesItem today = packTeamSales(todayMinTime, todayMaxTime, memberId);

        //List<JmUserSalesHistory> historyByUid = salesHistoryService.getHistoryByUid(memberId);

        //昨天业绩
        //TeamSalesItem yesterday = packSalesHistory(historyByUid, 1); //packTeamSales(yesterdayMinTime, yesterdayMaxTime, memberId);

        //7天以前业绩
        //TeamSalesItem sevenDaysAgo = packSalesHistory(historyByUid, 2);

        //30天以前业绩
        //TeamSalesItem thirtyDaysAgo = packSalesHistory(historyByUid, 3);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", memberId);
        JmUserStatisticsTeam team = statisticsTeamService.getOne(wrapper);
        team = team == null ? new JmUserStatisticsTeam() : team;
        JmUserStatisticsFenxiao fenxiao = statisticsFenxiaoService.getOne(wrapper);
        fenxiao = fenxiao == null ? new JmUserStatisticsFenxiao() : fenxiao;
        JmUserStatisticsSales sales = statisticsSalesService.getOne(wrapper);
        sales = sales == null ? new JmUserStatisticsSales() : sales;

        //昨日业绩
        TeamSalesItem yesterday = new TeamSalesItem(sales.getSalesYesterday(), sales.getSalesSelfYesterday(), sales.getSalesDirectYesterday(),
                sales.getSalesTeamYesterday());

        yesterday.setOrderNum(sales.getOrderCountYesterday());
        yesterday.setYongjin(fenxiao.getFenxiaoYesterday());
        yesterday.setInviteNum(team.getTeamTgYesterday());

        //7日业绩
        TeamSalesItem sevenDaysAgo = new TeamSalesItem(sales.getSalesWeek(), sales.getSalesSelfWeek(), sales.getSalesDirectWeek(),
                sales.getSalesTeamWeek());

        sevenDaysAgo.setOrderNum(sales.getOrderCountWeek());
        sevenDaysAgo.setYongjin(fenxiao.getFenxiaoWeek());
        sevenDaysAgo.setInviteNum(team.getTeamTgWeek());

        //30日业绩
        TeamSalesItem thirtyDaysAgo = new TeamSalesItem(sales.getSalesMonth(), sales.getSalesSelfMonth(), sales.getSalesDirectMonth(),
                sales.getSalesTeamMonth());

        thirtyDaysAgo.setOrderNum(sales.getOrderCountMonth());
        thirtyDaysAgo.setYongjin(fenxiao.getFenxiaoMonth());
        thirtyDaysAgo.setInviteNum(team.getTeamTgMonth());


        teamSalesAggregate.setItem(salesItem);
        teamSalesAggregate.setItemToday(today);
        teamSalesAggregate.setItemYesterday(yesterday);
        teamSalesAggregate.setItemSeven(sevenDaysAgo);
        teamSalesAggregate.setItemThirty(thirtyDaysAgo);

        return ResponseResult.success(teamSalesAggregate);

    }

    public TeamSalesItem packSalesHistory(List<JmUserSalesHistory> salesHistories, int historyType) {
        List<JmUserSalesHistory> filterList = salesHistories.stream().filter(s -> s.getHistoryType().equals(historyType)).collect(Collectors.toList());

        TeamSalesItem teamSalesItem = new TeamSalesItem();
        for (JmUserSalesHistory j : filterList) {
            BigDecimal directlySales = j.getDirectlySales();//直属消费
            //LocalDateTime createTime = j.getCreateTime();
            Integer inviteNum = j.getInviteNum();//邀请注册
            Integer orderNum = j.getOrderNum();
            BigDecimal selfSales = j.getSelfSales();//自己消费
            BigDecimal teamSales = j.getTeamSales();//团队消费
            BigDecimal yongjin = j.getYongjin();//收益
            BigDecimal sumConsume = directlySales.add(selfSales).add(teamSales);
            teamSalesItem = new TeamSalesItem(sumConsume, selfSales, directlySales, teamSales);
            teamSalesItem.setYongjin(yongjin);
            teamSalesItem.setInviteNum(inviteNum);
            teamSalesItem.setOrderNum(orderNum);
        }
        return teamSalesItem;
    }

    /**
     * 获得店铺业绩,客户明细 等头信息区域
     *
     * @param uid
     * @return
     */
    public Aggregate getAggregate(Integer uid) {
        JmUser byId = userService.checkUserExist(uid);
        Level level = byId.getLevel();
        int levelValue = level.getValue() == 4 ? 4 : level.getValue() + 1;
        JmUserLevelConfig config = levelConfigService.getById(levelValue);
        if (ObjectUtil.isEmpty(config)) {
            throw new BaseException("未查询等级配置信息!");
        }
        String childrenLevel = config.getChildrenLevel();//考核等级
        String[] chiLevelArr = childrenLevel.split(",");//用户考核等级配置
        Integer childrenNum = config.getChildrenNum();//对应等级的考核人数
        BigDecimal sales = config.getSales();//对应等级的考核业绩
        String addLevel = config.getAddLevel();//新增团队等级要求
        String[] addLevelArr = addLevel.split(",");
        Integer addNum = config.getAddNum();//新增团队人数要求


        JmUserTeam team = new JmUserTeam();
        team.setIsDel(CommonEnum.否);
        team.setTeamUid(uid);
        team.setJoinType(JoinType.直接邀请);
        QueryWrapper teamWrapper = WrapperUtil.getWrapper(null, team);//来筛选考核等级的查询条件
        QueryWrapper addTeamWrapper = WrapperUtil.getWrapper(null, team);//来筛选新增团队的查询条件


        JmUserSales userSales = new JmUserSales();
        userSales.setIsDel(CommonEnum.否);
        userSales.setUid(uid);
        userSales.setStatus(SalesStatus.正常);
        QueryWrapper salesWrapper = WrapperUtil.getWrapper(null, userSales);
        //salesWrapper.select("id","uid","level","buyer_id","buyer_level","status","consumer_type","order_sn","order_amount","pay_goods_price","origin_goods_price","create_time");
        if (ObjectUtil.isNotEmpty(chiLevelArr) && chiLevelArr.length > 0) {
            teamWrapper.in("level", chiLevelArr);
        }
        if (ObjectUtil.isNotEmpty(addLevelArr) && addLevelArr.length > 0) {
            addTeamWrapper.in("level", addLevelArr);
            addTeamWrapper.ge("join_time", "2020-09-09 00:00:00");//固定一个时间以后的记录
        }
        BigDecimal sumSales = salesService.getSumSales(salesWrapper);//用户已完成的业绩
        int chilCount = teamService.getSumChiNum(teamWrapper);//查询出已完成考核人数
        int addCount = teamService.getSumChiNum(addTeamWrapper);//查询出已完成新增团队人数
        int remainderNum = childrenNum - chilCount < 0 ? 0 : childrenNum - chilCount;//剩余考核人数
        int remainderAddNum = addNum - addCount < 0 ? 0 : addNum - addCount;//剩余新增团队人数
        BigDecimal remainderSales = sales.subtract(sumSales).doubleValue() <= 0.00 ? new BigDecimal(0.00) : sales.subtract(sumSales);//剩余考核业绩
        Aggregate aggregate = new Aggregate(level, childrenNum, chilCount, remainderNum, sales, sumSales, remainderSales, addNum, addCount, remainderAddNum);
        return aggregate;
    }

    @Autowired
    IJmUserTeamHistoryService historyService;

    @GetMapping("/index")
    @ApiOperation(value = "我的团队首页数据展示", response = TeamAggregate.class)
    public ResponseResult index() {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
//        Integer memberId = 1;
        Aggregate aggregate = getAggregate(memberId);
        TeamAggregate teamAggregate = new TeamAggregate(aggregate);

        LocalDateTime todayMaxTime = LocalDateTimeUtil.getNBeforeMaxTime(0);//今天的最大时间
        LocalDateTime todayMinTime = LocalDateTimeUtil.getNBeforeMinTime(0);//今天的最小事件

        TeamItem teamItem = packTeam(null, null, memberId);
        //今天
        TeamItem today = packTeam(todayMinTime, todayMaxTime, memberId);

       /* //获得历史记录
        List<JmUserTeamHistory> teamHistoryByUid = historyService.getTeamHistoryByUid(memberId);

        //昨天
        TeamItem yesterday = packTeamHistory(teamHistoryByUid, 1);

        //7天以前
        TeamItem sevenDaysAgo = packTeamHistory(teamHistoryByUid, 2);

        //30天以前
        TeamItem thirtyDaysAgo = packTeamHistory(teamHistoryByUid, 3);*/
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", memberId);
        JmUserStatisticsTeam team = statisticsTeamService.getOne(wrapper);
        team = team == null ? new JmUserStatisticsTeam() : team;
        JmUserStatisticsFenxiao fenxiao = statisticsFenxiaoService.getOne(wrapper);
        fenxiao = fenxiao == null ? new JmUserStatisticsFenxiao() : fenxiao;
        JmUserStatisticsSales sales = statisticsSalesService.getOne(wrapper);
        sales = sales == null ? new JmUserStatisticsSales() : sales;

        TeamItem yesterday = new TeamItem(team.getTeamTgYesterday(), team.getTeamZcYesterday(), team.getTeamYesterday(),
                sales.getOrderCountYesterday(), sales.getSalesYesterday(), fenxiao.getFenxiaoYesterday());
        TeamItem sevenDaysAgo = new TeamItem(team.getTeamTgWeek(), team.getTeamZcWeek(), team.getTeamWeek(), sales.getOrderCountWeek(), sales.getSalesWeek(), fenxiao.getFenxiaoWeek());
        TeamItem thirtyDaysAgo = new TeamItem(team.getTeamTgMonth(), team.getTeamZcMonth(), team.getTeamMonth(), sales.getOrderCountMonth(), sales.getSalesMonth(), fenxiao.getFenxiaoMonth());

        teamAggregate.setTeamItem(teamItem);
        teamAggregate.setToday(today);
        teamAggregate.setYesterday(yesterday);
        teamAggregate.setSevenDay(sevenDaysAgo);
        teamAggregate.setThirtyDay(thirtyDaysAgo);

        return ResponseResult.success(teamAggregate);
    }

    public TeamItem packTeamHistory(List<JmUserTeamHistory> teamHistories, int historyType) {
        //类型：1.昨天，2.7天前，3.30天前

        List<JmUserTeamHistory> filterList = teamHistories.stream().filter(s -> s.getHistoryType().equals(historyType)).collect(Collectors.toList());
        TeamItem teamItem = new TeamItem();
        for (JmUserTeamHistory jmUserTeamHistory : filterList) {
            Integer directlyNum = jmUserTeamHistory.getDirectlyNum();//推广
            Integer indirectlyNum = jmUserTeamHistory.getIndirectlyNum();//注册
            Integer teamNum = jmUserTeamHistory.getTeamNum();//全部客户
            Integer orderNum = jmUserTeamHistory.getOrderNum();
            BigDecimal yongjin = jmUserTeamHistory.getYongjin();//收益
            BigDecimal sales = jmUserTeamHistory.getSales();//业绩
            teamItem = new TeamItem(directlyNum, indirectlyNum, teamNum, orderNum, yongjin, sales);
        }
        return teamItem;
    }

    private Map<String, QueryWrapper> packWrapper(Integer teamUid) {
        Map<String, QueryWrapper> map = new HashMap<>();

        JmUserSales sales = new JmUserSales();
        sales.setUid(teamUid);
        sales.setIsDel(CommonEnum.否);
        sales.setStatus(SalesStatus.正常);
        QueryWrapper salesWrapper = WrapperUtil.getWrapper(null, sales);

        map.put("salesWrapper", salesWrapper);

        JmUserFenxiao fenxiao = new JmUserFenxiao();
        fenxiao.setIsDel(CommonEnum.否);
        fenxiao.setUid(teamUid);
        fenxiao.setStatus(FenXiaoStatus.已结算);
        QueryWrapper fxWrapper = WrapperUtil.getWrapper(null, fenxiao);

        map.put("fxWrapper", fxWrapper);

        JmUserTeam team = new JmUserTeam();
        team.setIsDel(CommonEnum.否);
        team.setTeamUid(teamUid);
        QueryWrapper teamWrapper = WrapperUtil.getWrapper(null, team);

        map.put("teamWrapper", teamWrapper);

        return map;

    }

    public TeamItem packTeam(LocalDateTime beginTime, LocalDateTime endTime, Integer teamUid) {

        Map<String, QueryWrapper> map = this.packWrapper(teamUid);

        QueryWrapper salesWrapper = map.get("salesWrapper");

        QueryWrapper fxWrapper = map.get("fxWrapper");

        QueryWrapper teamWrapper = map.get("teamWrapper");

        teamWrapper.groupBy("join_type");
        if (ObjectUtil.isAllNotEmpty(beginTime, endTime)) {
            salesWrapper.ge("create_time", beginTime);
            salesWrapper.lt("create_time", endTime);
            teamWrapper.ge("join_time", beginTime);
            teamWrapper.lt("join_time", endTime);
            fxWrapper.ge("create_time", beginTime);
            fxWrapper.lt("create_time", endTime);
        }
        BigDecimal sumYongJin = fenxiaoService.getSumYongJin(fxWrapper);//成交收益
        BigDecimal sumSales = salesService.getSumSales(salesWrapper);//累计业绩
        Integer sumOrderNum = salesService.getSumOrderNum(salesWrapper);//订单数量
        //邀请人数
        List<CommonGroup> teamNumsByInviterType = teamService.getTeamNumsByInviterType(teamWrapper);
        int tg = 0, zc = 0, all = 0;

        for (CommonGroup commonGroup : teamNumsByInviterType) {
            Integer type = commonGroup.getType();
            Integer count = commonGroup.getCount();
            all += count;
            JoinType item = JoinType.getItem(type);
            if (item.equals(JoinType.直接邀请)) {
                tg += count;
            } else {
                zc += count;
            }
        }
        TeamItem teamItem = new TeamItem(tg, zc, all, sumOrderNum, sumYongJin, sumSales);
        return teamItem;
    }

    @PostMapping("/myTeam")
    @ApiOperation("我的团队信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "needMobile", value = "是否为根据手机号查询请求;0=否,1=是", required = true),
            @ApiImplicitParam(name = "size", value = "分页大小", required = true),
            @ApiImplicitParam(name = "current", value = "分页大小", required = true),
            @ApiImplicitParam(name = "onlyDirect", value = "是否只需要显示直属下级;true,false")
    })
    public ResponseResult myTeam(@Validated MyTeamQueryRequest request, Integer needMobile,
                                 Integer size, Integer current, boolean onlyDirect) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        userService.checkUserExist(memberId);
        Integer sign = request.getSign();
        Page page = new Page(current, size);
        if (StrUtil.isNotBlank(request.getEndTime())) {
            try {
                Date endDate = DateUtil.parse(request.getEndTime(), "yyyy-MM");
                endDate = DateUtil.offsetMonth(endDate, 1);
                request.setEndTime(DateUtil.format(endDate, "yyyy-MM"));
            } catch (Exception e) {
                throw new BaseException(500, "截止日期时间格式错误!");
            }
        }
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, request);
        /**
         * beginTime与endTime为空时,需要判断是否查询今日,昨日,7天,30天的数据.
         *
         */

        if (StrUtil.isEmpty(request.getBeginTime())
                && StrUtil.isEmpty(request.getEndTime()) &&
                ArrayUtil.contains(new int[]{0, 1, 7, 30}, sign)) {
            LocalDateTime nBeforeMinTime = LocalDateTimeUtil.getNBeforeMinTime(sign);
            LocalDateTime nBeforeMaxTime = null;
            if (sign != 0) {
                nBeforeMaxTime = LocalDateTimeUtil.getNBeforeMaxTime(1);
            }
            WrapperUtil.setTimeQueryWrapper(wrapper, nBeforeMinTime, nBeforeMaxTime, "join_time");
        }
        if (ObjectUtil.isNotEmpty(request.getLevels())) {
            wrapper.in("level", request.getLevels());
        }
        if (needMobile != null && needMobile == 1)
            wrapper.eq("mobile", request.getMobile());

        wrapper.orderByDesc("id");
        page = teamService.getMyTeam(page, wrapper, memberId, onlyDirect);

        return ResponseResult.success(page);
    }


    @PostMapping("/teamDetail")
    @ApiOperation("团员明细信息")
    @ApiImplicitParams(@ApiImplicitParam(name = "time", value = "查询时间", example = "2020-05-05"))
    public ResponseResult teamDetail(
            @ApiParam(required = true, value = "用户id") @RequestParam Integer uid,
            @ApiParam(required = true, value = "当前页") @RequestParam Integer current,
            @ApiParam(required = true, value = "显示数量") @RequestParam Integer size,
            @ApiParam(required = true, value = "查询类型:0=业绩,1=收益") @RequestParam Integer type, String time) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser inviter = userService.checkUserExist(memberId);//登录用户
        JmUser member = userService.checkUserExist(uid);//被查询的用户

        //检验用户直属上级
        JmUserInvite invite = inviteService.getInviteByUid(uid);//直属邀请信息
        if (ObjectUtil.isEmpty(invite) || !ObjectUtil.equal(memberId, invite.getInviteUid())) {
            return ResponseResult.error("上级关系错误，不允许查询!");
        }

        Map map = new HashMap();
        //map.put("inviter",inviter);
        map.put("memberId", member.getId());
        map.put("memberName", member.getName());
        map.put("memberTrueName", member.getTruename());
        map.put("memberWeChat", member.getWechatNum());
        map.put("memberLevel", member.getLevel());
        map.put("memberAvatar", member.getAvatar());
        map.put("inviterUserName", inviter.getName());//所属上级
        map.put("inviterId", inviter.getId());
        map.put("mobile", member.getMobile());
        map.put("joinTime", invite.getCreateTime().format(DateTimeFormatter.ofPattern(LocalDateTimeConfig.DEFAULT_DATE_FORMAT)));
        if (type.equals(0)) {
            JmUserSales sales = new JmUserSales();
            sales.setUid(memberId);
            sales.setBuyerId(member.getId());
            sales.setIsDel(CommonEnum.否);
            sales.setStatus(SalesStatus.正常);
            QueryWrapper wrapper = WrapperUtil.getWrapper(null, sales);
            getTeamUserSales(wrapper, memberId, current, size, map, time);
        } else {
            JmUserFenxiao fenxiao = new JmUserFenxiao();
            fenxiao.setUid(memberId);
            fenxiao.setBuyerId(member.getId());
            fenxiao.setIsDel(CommonEnum.否);
            QueryWrapper wrapper = WrapperUtil.getWrapper(null, fenxiao);
            wrapper.ne("status", FenXiaoStatus.失效);
            getTeamUserFenxiao(wrapper, current, size, map, time);
        }
        return ResponseResult.success(map);
    }

    @PostMapping("/salesDetail")
    @ApiOperation("累计业绩明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "查询时间", example = "2020-05-05"),
            @ApiImplicitParam(name = "type", value = "消费类型"),
            @ApiImplicitParam(name = "mobile", value = "手机号"),
    })
    public ResponseResult salesDetail(@ApiParam(required = true, value = "当前页") @RequestParam Integer current,
                                      @ApiParam(required = true, value = "显示数量") @RequestParam Integer size,
                                      String mobile, Integer type, String time) {
        Integer memberId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        userService.checkUserExist(memberId);//登录用户
        JmUserSales userSales = new JmUserSales();//构建查询条件
        userSales.setUid(memberId);
        userSales.setIsDel(CommonEnum.否);
        userSales.setStatus(SalesStatus.正常);
        ConsumerType consumerType = Convert.toEnum(ConsumerType.class, type);
        /*if(consumerType==null)
            throw new BaseException(500,"消费类型错误!");*/
        userSales.setConsumerType(consumerType);
        if (StrUtil.isNotEmpty(mobile)) {
            JmUser userByMobile = userService.getUserByMobile(mobile);//查询手机号的用户
            if (ObjectUtil.isNotEmpty(userByMobile)) {
                //检验用户直属上级
                //JmUserInvite invite = inviteService.getInviteByUid(uid);//直属邀请信息
//                Integer inviterId = userByMobile.getInviterId();
                Integer buyerId = userByMobile.getId();
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("uid", memberId);
                wrapper.eq("buyer_id", buyerId);
                wrapper.eq("status", 1);
                wrapper.eq("is_del", 0);
                List<JmUserSales> list = salesService.list(wrapper);
                if (ObjectUtil.isEmpty(list)) {
                    return ResponseResult.error("查询手机号未向当前用户提供任何收益!");
                }
                userSales.setBuyerId(buyerId);
            } else {
                return ResponseResult.error("查询用户不存在!");
            }

        }
        QueryWrapper salesWrapper = WrapperUtil.getWrapper(null, userSales);
        Map map = new HashMap();
        getTeamUserSales(salesWrapper, memberId, current, size, map, time);
        return ResponseResult.success(map);
    }


    public void getTeamUserFenxiao(QueryWrapper wrapper, Integer current, Integer size, Map map, String time) {
        if (StrUtil.isNotEmpty(time)) {
            LocalDate parse = LocalDate.parse(time);
            LocalDateTime minTimeByDate = LocalDateTimeUtil.getMinTimeByDate(parse);
            LocalDateTime maxTimeByDate = LocalDateTimeUtil.getMaxTimeByDate(parse);
            WrapperUtil.setTimeQueryWrapper(wrapper, minTimeByDate, maxTimeByDate);
        }
        wrapper.orderByDesc("id");
        IPage page = fenxiaoService.getFenXiaoDetail(new Page(current, size), wrapper);
        BigDecimal sumYongJin = fenxiaoService.getSumYongJin(wrapper);
        map.put("sumYongJin", sumYongJin);
        map.put("page", page);
    }

    public void getTeamUserSales(QueryWrapper wrapper, Integer inviterId, Integer current, Integer size, Map map, String time) {
        if (StrUtil.isNotEmpty(time)) {
            LocalDate parse = LocalDate.parse(time);
            LocalDateTime minTimeByDate = LocalDateTimeUtil.getMinTimeByDate(parse);
            LocalDateTime maxTimeByDate = LocalDateTimeUtil.getMaxTimeByDate(parse);
            WrapperUtil.setTimeQueryWrapper(wrapper, minTimeByDate, maxTimeByDate);
        }
        BigDecimal sumSales = salesService.getSumSales(wrapper);//用户的总业绩

        wrapper.orderByDesc("id");
        Page page = salesService.getSalesByInviterId(new Page(current, size), inviterId, wrapper);
        map.put("sumSales", sumSales);
        map.put("page", page);
    }


    public TeamSalesItem packTeamSales(LocalDateTime beginTime, LocalDateTime endTime, Integer teamUid) {
        Map<String, QueryWrapper> map = this.packWrapper(teamUid);

        QueryWrapper salesWrapper = map.get("salesWrapper");

        QueryWrapper fxWrapper = map.get("fxWrapper");

        QueryWrapper teamWrapper = map.get("teamWrapper");

        int inviterNum = 0;
        BigDecimal sumYongJin = new BigDecimal(0.00);
        if (ObjectUtil.isAllNotEmpty(beginTime, endTime)) {
            salesWrapper.ge("create_time", beginTime);
            salesWrapper.lt("create_time", endTime);
            teamWrapper.ge("join_time", beginTime);
            teamWrapper.lt("join_time", endTime);
            fxWrapper.ge("create_time", beginTime);
            fxWrapper.lt("create_time", endTime);
            //只有设置时间查询时,才会查所有的注册人数, 和成交收益
            inviterNum = teamService.count(teamWrapper);//邀请注册人数
            sumYongJin = fenxiaoService.getSumYongJin(fxWrapper);//获得成交收益
        }


        int orderNum = salesService.getSumOrderNum(salesWrapper);//查询订单数量

//        salesWrapper = WrapperUtil.getWrapper(salesWrapper, sales);
        salesWrapper.groupBy("consumer_type");
        List<CommonGroup> sumSalesByConsumerType = salesService.getSumSalesByConsumerType(salesWrapper);
        BigDecimal selfConsume = new BigDecimal(0.00);//自购消费业绩
        BigDecimal directConsume = new BigDecimal(0.00);//直属消费业绩
        BigDecimal inDirectConsume = new BigDecimal(0.00);//团队消费业绩
        BigDecimal sumConsume = new BigDecimal(0.00);//用户总业绩

        for (CommonGroup commonGroup : sumSalesByConsumerType) {
            BigDecimal price = commonGroup.getPrice();
            Integer type = commonGroup.getType();
            if (type.equals(ConsumerType.自购.getValue())) {
                selfConsume = selfConsume.add(price);
            } else if (type.equals(ConsumerType.团队.getValue())) {
                inDirectConsume = inDirectConsume.add(price);
            } else {
                directConsume = directConsume.add(price);
            }
            sumConsume = sumConsume.add(price);
        }


        TeamSalesItem salesData = new TeamSalesItem(sumConsume, selfConsume, directConsume, inDirectConsume);
        salesData.setOrderNum(orderNum);
        salesData.setInviteNum(inviterNum);
        salesData.setYongjin(sumYongJin);
        return salesData;
    }


    @Autowired
    IJmFlowLogService flowLogService;

    @ApiOperation("更新浏览记录")
    @PostMapping("/updateFlow")
//    @IgnoreUrlsAnnon("/updateFlow")
    public ResponseResult updateFlow(JmFlowUpdateRequest request) {
        Integer flowUserId = request.getFlowUserId();
        Integer shareUserId = request.getShareUserId();
        userService.checkUserExist(shareUserId);
        userService.checkUserExist(flowUserId);
        JmFlowLog flowLog = new JmFlowLog();
        flowLog.setIsDel(CommonEnum.否);
        BeanUtils.copyProperties(request, flowLog);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, flowLog);
        JmFlowLog one = flowLogService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(one)) {
            Integer flowNum = one.getFlowNum();
            one.setFlowNum(flowNum + 1);
        } else {
            one = flowLog;
        }
        one.setCreateTime(LocalDateTime.now());
        flowLogService.saveOrUpdate(one);
        return ResponseResult.success();
    }

    @ApiOperation("店铺流量--访问用户")
    @PostMapping("/userFlow")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "date", value = "查询月份", example = "2020-05"),
    })
    public TableDataInfo userFlow(String date,
                                  @ApiParam(required = true, value = "当前页") @RequestParam Integer current,
                                  @ApiParam(required = true, value = "每页显示数量") @RequestParam Integer size) {
        Integer apiUserId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        //userService.checkUserExist(apiUserId);
        JmFlowLog flowLog = new JmFlowLog();
        flowLog.setIsDel(CommonEnum.否);
        flowLog.setShareUserId(apiUserId);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, flowLog);
        if (ObjectUtil.isNotEmpty(date)) {
            String beginDate = date + "-01";
            String endDate = date + "-31";
            beginDate.intern();
            endDate.intern();
            wrapper.ge("create_time", beginDate);
            wrapper.le("create_time", endDate);
        }
        Page page = flowLogService.getPage(new Page(current, size), wrapper);
        TableDataInfo dataTableInfo = PageService.getDataTableInfo(page);
        return dataTableInfo;
    }

    @DubboReference(check = false)
    CommodityApi goodService;

    @ApiOperation("店铺流量--商品浏览量")
    @PostMapping("/goodFlow")
    public TableDataInfo goodFlow(@ApiParam(required = true, value = "排序方式", example = "desc 或 asc") @RequestParam String orderByType,
                                  @ApiParam(required = true, value = "当前页") @RequestParam Integer current,
                                  @ApiParam(required = true, value = "每页显示数量") @RequestParam Integer size) {
        Integer apiUserId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        //userService.checkUserExist(apiUserId);
        JmFlowLog flowLog = new JmFlowLog();
        flowLog.setIsDel(CommonEnum.否);
        flowLog.setShareUserId(apiUserId);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, flowLog);
        if (!StrUtil.equals(orderByType, "desc")) {
            orderByType = "asc";
        }


        Page<JmFlowGoodResponse> page = flowLogService.getGoodBrowsePage(new Page(current, size), wrapper, orderByType);
        List<JmFlowGoodResponse> records = page.getRecords();
        Map<Long, List<JmFlowGoodResponse>> responseMap = records.stream().collect(Collectors.groupingBy(JmFlowGoodResponse::getGoodsId));
        List<Long> goodIds = responseMap.keySet().stream().collect(Collectors.toList());
        try {
            List<GoodsSpuDTO> goodsInfo=goodService.getGoodsSpuByIds(goodIds,Boolean.TRUE, null);
            for(GoodsSpuDTO goods:goodsInfo){
                for(JmFlowGoodResponse record:records){
                    if(goods.getGoodsId().equals(record.getGoodsId())){
                        record.setName(goods.getGoodsName());
                        record.setImg(goods.getGoodsImage());
                        record.setClassifyId(goods.getCategory());
                        record.setClassifyName(goods.getCategoryName());
                        record.setGoodsState(goods.getGoodsState());
                        record.setGoodsPrice(goods.getGoodsPrice());
                        record.setGoodsMarketprice(goods.getGoodsMarketprice());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new BaseException(StrUtil.format("商品服务调用异常!{}", e.getMessage()));
        }

        page.setRecords(records);
        TableDataInfo dataTableInfo = PageService.getDataTableInfo(page);
        return dataTableInfo;
    }

    @ApiOperation("店铺流量--用户的商品浏览记录")
    @PostMapping("/userGoodsFlow")
    public TableDataInfo userGoodsFlow(@ApiParam(required = true, value = "浏览人id") @RequestParam Integer uid,
                                       @ApiParam(required = true, value = "当前页") @RequestParam Integer current,
                                       @ApiParam(required = true, value = "每页显示数量") @RequestParam Integer size) {
        Integer apiUserId = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        //userService.checkUserExist(uid);
        JmFlowLog flowLog = new JmFlowLog();
        flowLog.setIsDel(CommonEnum.否);
        flowLog.setShareUserId(apiUserId);
        flowLog.setFlowUserId(uid);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, flowLog);
        Page page = flowLogService.getUserGoodFlowPage(new Page(current, size), wrapper);

        List<UserGoodFlowResponse> records = page.getRecords();
        Map<Long, List<UserGoodFlowResponse>> responseMap = records.stream().collect(Collectors.groupingBy(UserGoodFlowResponse::getGoodsId));
        List<Long> goodIds = responseMap.keySet().stream().collect(Collectors.toList());
        List<GoodsSpuDTO> goodsSpuByIds = new ArrayList<>();
        try {
            goodsSpuByIds.addAll(goodService.getGoodsSpuByIds(goodIds, Boolean.TRUE, null));
            records.clear();
        } catch (Exception e) {
            throw new BaseException(StrUtil.format("商品服务调用异常!{}", e.getMessage()));
        }
        for (GoodsSpuDTO goodsSpuById : goodsSpuByIds) {
            Long goodsId = goodsSpuById.getGoodsId();
            List<UserGoodFlowResponse> jmFlowGoodResponses = responseMap.get(goodsId);
            for (UserGoodFlowResponse userGoodFlowResponse : jmFlowGoodResponses) {
                userGoodFlowResponse.setName(goodsSpuById.getGoodsName());
                userGoodFlowResponse.setImg(goodsSpuById.getGoodsImage());
                userGoodFlowResponse.setClassifyId(goodsSpuById.getCategory());
                userGoodFlowResponse.setClassifyName(goodsSpuById.getCategoryName());
                userGoodFlowResponse.setGoodsState(goodsSpuById.getGoodsState());
                userGoodFlowResponse.setGoodsPrice(goodsSpuById.getGoodsPrice());
                userGoodFlowResponse.setGoodsMarketprice(goodsSpuById.getGoodsMarketprice());
            }
            records.addAll(jmFlowGoodResponses);
        }
        page.setRecords(records);
        TableDataInfo dataTableInfo = PageService.getDataTableInfo(page);
        return dataTableInfo;
    }
}
